/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.doc.sender.ui;


import com.database.entity.PdfFiles;
import database.senderUtil;
import java.awt.Component;
import java.awt.Point;
import java.awt.event.ActionEvent;
import java.util.List;
import java.util.Vector;
import javax.swing.*;
import javax.swing.JButton;
import javax.swing.table.*;
import org.hibernate.Query;
import org.hibernate.Transaction;
import org.hibernate.Session;


/**
 *
 * @author parent
 */
public class ListUserFrame extends javax.swing.JFrame {

    /**
     * Creates new form ListDocumentFrame
     */
    private static String TITLE="Daftar User";
    
    int selectedFileId;
    JPopupMenu LisPop;
    int GroupActive;
//    public ListDocumentFrame() {
//        initComponents();
//    }
    Action editAction = new AbstractAction("Edit") {

        @Override
        public void actionPerformed(ActionEvent evt) {
            //doOpen();
        }
    };
    Action deleteAction = new AbstractAction("Delete") {

        @Override
        public void actionPerformed(ActionEvent evt) {
            //doOpen();
        }
    };
    Action showUserAction = new AbstractAction("Show Detail") {

        @Override
        public void actionPerformed(ActionEvent evt) {
            ViewContent();
        }
    };
    public void ViewContent(){
        
    }
    public ListUserFrame(){
        this.setTitle(TITLE);
       
        initComponents();
        LisPop=new JPopupMenu();
        LisPop.add(editAction);
        LisPop.add(deleteAction);
        LisPop.add(showUserAction);
    }
    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jToolBar1 = new javax.swing.JToolBar();
        jLabel1 = new javax.swing.JLabel();
        txtKeyword = new javax.swing.JTextField();
        btnSearch = new javax.swing.JButton();
        btnRefresh = new javax.swing.JButton();
        jSeparator1 = new javax.swing.JToolBar.Separator();
        btnClose = new javax.swing.JButton();
        tscrollTable = new javax.swing.JScrollPane();
        resultTable = new javax.swing.JTable();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowOpened(java.awt.event.WindowEvent evt) {
                formWindowOpened(evt);
            }
        });

        jToolBar1.setRollover(true);

        jLabel1.setText("Keyword :");
        jToolBar1.add(jLabel1);

        txtKeyword.setPreferredSize(new java.awt.Dimension(160, 32));
        jToolBar1.add(txtKeyword);

        btnSearch.setText("Search");
        btnSearch.setFocusable(false);
        btnSearch.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        btnSearch.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        btnSearch.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnSearchActionPerformed(evt);
            }
        });
        jToolBar1.add(btnSearch);

        btnRefresh.setText("Refresh");
        btnRefresh.setFocusable(false);
        btnRefresh.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        btnRefresh.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        btnRefresh.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnRefreshActionPerformed(evt);
            }
        });
        jToolBar1.add(btnRefresh);
        jToolBar1.add(jSeparator1);

        btnClose.setText("Tutup");
        btnClose.setFocusable(false);
        btnClose.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        btnClose.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        btnClose.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnCloseActionPerformed(evt);
            }
        });
        jToolBar1.add(btnClose);

        resultTable.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Id", "GroupName", "Description"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.String.class, java.lang.String.class, java.lang.String.class
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }
        });
        resultTable.getTableHeader().setReorderingAllowed(false);
        resultTable.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseReleased(java.awt.event.MouseEvent evt) {
                resultTableMouseReleased(evt);
            }
        });
        tscrollTable.setViewportView(resultTable);
        resultTable.getColumnModel().getColumn(0).setPreferredWidth(40);
        resultTable.getColumnModel().getColumn(2).setPreferredWidth(120);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jToolBar1, javax.swing.GroupLayout.DEFAULT_SIZE, 664, Short.MAX_VALUE)
            .addComponent(tscrollTable, javax.swing.GroupLayout.DEFAULT_SIZE, 664, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jToolBar1, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(tscrollTable, javax.swing.GroupLayout.DEFAULT_SIZE, 316, Short.MAX_VALUE))
        );

        pack();
        java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
        java.awt.Dimension dialogSize = getSize();
        setLocation((screenSize.width-dialogSize.width)/2,(screenSize.height-dialogSize.height)/2);
    }// </editor-fold>//GEN-END:initComponents

    private void btnCloseActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCloseActionPerformed
        // TODO add your handling code here:
        this.dispose();
    }//GEN-LAST:event_btnCloseActionPerformed

public void LoadTable(){
    PopulateToList ppl=new PopulateToList();
    DefaultTableModel model=ppl.GetUserTableModel(txtKeyword.getText());
    if (model!=null){
      resultTable.setModel(model);     
    }
    
}    
    
    public PdfFiles getFileInRow(int id){
        Session session = senderUtil.getSessionFactory().openSession();
        Transaction transaction = null;
        try {
            transaction = session.beginTransaction();
            String queryString = "from PdfFiles where id=:id";
            Query query = session.createQuery(queryString);
            query.setInteger("id", id);
            PdfFiles pdfs=(PdfFiles)query.uniqueResult();
            transaction.commit();
            if(pdfs!=null){
                // System.out.println("File sudah ada");
                return pdfs;
               
            } else return null;
            
        } catch (Exception e){
            e.printStackTrace();
            return null;
        }
    }
    private void formWindowOpened(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowOpened
        // TODO add your handling code here:
        LoadTable();
    }//GEN-LAST:event_formWindowOpened

    private void resultTableMouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_resultTableMouseReleased
        // TODO add your handling code here:
        if(evt.isPopupTrigger()){
            LisPop.show(evt.getComponent(), evt.getX(), evt.getY());
            DefaultTableModel model=(DefaultTableModel)resultTable.getModel();
            int row=resultTable.rowAtPoint(new Point(evt.getX(),evt.getY()));
            selectedFileId=(int)model.getValueAt(row, 0);
//            System.out.println(model.getValueAt(row, 1));
          }
    }//GEN-LAST:event_resultTableMouseReleased

    private void btnSearchActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSearchActionPerformed
        // TODO add your handling code here:
        LoadTable();
    }//GEN-LAST:event_btnSearchActionPerformed

    private void btnRefreshActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnRefreshActionPerformed
        // TODO add your handling code here:
        LoadTable();
    }//GEN-LAST:event_btnRefreshActionPerformed
    class ShowBlobCellRenderer extends JPanel implements TableCellRenderer {
        public Component getTableCellRendererComponent(
                            final JTable table, Object value,
                            boolean isSelected, boolean hasFocus,
                            int row, int column) {
                this.add( new JTextField( value.toString()  ) );
                this.add( new JButton("Show"));
                this.add( new JButton("Send"));
                return this;
        }
}
    private void displayResult(List resultList) {
    Vector<String> tableHeaders = new Vector<String>();
    Vector tableData = new Vector();
    tableHeaders.add("Id"); 
    tableHeaders.add("FileName");
    tableHeaders.add("Source");
    tableHeaders.add("Date");
    tableHeaders.add("Content");
//    DefaultTableModel model= (DefaultTableModel)resultTable.getModel();
    for(Object o : resultList) {
        PdfFiles Pdfs = (PdfFiles)o;
        Vector<Object> oneRow = new Vector<Object>();
        oneRow.add(Pdfs.getId());
        oneRow.add(Pdfs.getFileName());
        //oneRow.add("[BLOB "+Integer.toString(PdfFiles.getId())+"]");
        oneRow.add(Pdfs.getIpAddress());
        oneRow.add(Pdfs.getDateCreated());
        oneRow.add("(BLOB)");
        tableData.add(oneRow);
    }
    resultTable.setModel(new DefaultTableModel(tableData, tableHeaders));
//    TableColumnModel tcm=resultTable.getColumnModel();
//    TableColumn column=tcm.getColumn(0);
//    column.setWidth(40);
    
//    column.setCellRenderer(new ButtonRenderer());
//    column.setCellEditor(new ButtonEditor(new JCheckBox()));
   // column.setCellRenderer(new ShowBlobCellRenderer());
}
    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /*
         * Set the Nimbus look and feel
         */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /*
         * If Nimbus (introduced in Java SE 6) is not available, stay with the
         * default look and feel. For details see
         * http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(ListUserFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(ListUserFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(ListUserFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(ListUserFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /*
         * Create and display the form
         */
        
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                
               new ListUserFrame().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnClose;
    private javax.swing.JButton btnRefresh;
    private javax.swing.JButton btnSearch;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JToolBar.Separator jSeparator1;
    private javax.swing.JToolBar jToolBar1;
    private javax.swing.JTable resultTable;
    private javax.swing.JScrollPane tscrollTable;
    private javax.swing.JTextField txtKeyword;
    // End of variables declaration//GEN-END:variables
}
